<?php
// 本类由系统自动生成，仅供测试用途
class IndexAction extends Action {
    // const TOTAL=5;
    // const NUMBER=10;
    public function checklogin() {
        if (empty($_SESSION['userid'])) {
            $appid=C('appid');
            $redirect_uri=U('Index/wx_back','','',false,true);
            $success_url='';
            die(header('location:https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$redirect_uri.'&response_type=code&scope=snsapi_userinfo&state='.$success_url.'#wechat_redirect'));
        }
    }
    
    public function index(){
        $this->checklogin();
        $this->get_wx_share();
        $this->display('jump');
    }
    public function monilogin(){
        $_SESSION['userid'] = '10533';
        $_SESSION['openid'] = 'oQzrmjpedUtjfGfPlN1G4VNgiXSg';
        }


    /**
     * 模拟post请求
     * Enter description here ...
     * @param unknown_type $url 请求地址
     * @param unknown_type $postdata 要提交的数据
     * @param unknown_type $options 批量设置cURL传输选项
     */
    function curl_post($url='', $postdata='', $options=array()){
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 25);
        if (!empty($options)){
            curl_setopt_array($ch, $options);
        }
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }




    //微信回调
    public function wx_back() {
        //获取openid
        //$auth = curl_get('https://api.weixin.qq.com/sns/oauth2/access_token?appid='.C('appid').'&secret='.C('appsecret').'&code='.$_GET['code'].'&grant_type=authorization_code');
        $auth = $this->curl_post('https://api.weixin.qq.com/sns/oauth2/access_token?appid='.C('appid').'&secret='.C('appsecret').'&code='.$_GET['code'].'&grant_type=authorization_code');
        file_put_contents('get.txt', json_encode($_GET));
        file_put_contents('auth.txt', json_encode($auth));
        $auth = json_decode($auth,true);
        if (empty($auth) || !empty($auth['errcode'])) die('Fatal Error');
        
        //缓存openid
        $_SESSION['openid'] = $auth['openid'];
        $user_Model=M('User');
        $userid=$user_Model->where("openid='%s'",$auth['openid'])->getField('uid');
        if (empty($userid)) {
            //$result = curl_get('https://api.weixin.qq.com/sns/userinfo?access_token='.$auth['access_token'].'&openid='.$auth['openid'].'&lang=zh_CN');
//          $result = file_get_contents('https://api.weixin.qq.com/sns/userinfo?access_token='.$auth['access_token'].'&openid='.$auth['openid'].'&lang=zh_CN');
//          file_put_contents('result.txt', json_encode($result));
//          $result = json_decode($result,true);
//          if (empty($result) || !empty($result['errcode'])) die('Fatal Error');
            
            $data=array(
                    'openid'=>$auth['openid'],
//                  'nickname'=>$result['nickname'],
//                  'sex'=>$result['sex'],
//                  'headimgurl'=>$result['headimgurl'],
//                  'province'=>$result['province'],
//                  'city'=>$result['city'],
//                  'province'=>$result['province'],
            );
            $userid=$user_Model->add($data);
        }
        $_SESSION['userid']=$userid;
        
        $this->redirect('Index/index');
    }
    
    public function show_2999() {
        $this->checklogin();
        $this->get_wx_share();
        $this->display('hongbao1');
    }
    
    public function show_3599() {
        $this->checklogin();
        $this->get_wx_share();
        $this->display('hongbao2');
    }
    
    public function catch_index() {
        $this->checklogin();
        $this->get_wx_share();
        $this->display('index1');
    }
    
    //发红包
    public function give_redbag() {

        $this->checklogin();
        $this->get_wx_share();
        header("Content-type:text/html;charset=utf-8");

        $total=C('total');
        $number=C('number');

        //0点到8点不能参与活动
        $time=date("H");
        if ($time>0 && $time<8) {
            die('<script>alert("0时-8时不能抢红包");history.back()</script>');
        }
        //每个用户每天只能领一个红包
        $userid=$_SESSION['userid'];
        $canyu_model=M('Canyu');
        $map['create_time']=array('like',date('Y-m-d').'%');
        $day_count=$canyu_model->where($map)->count();
        $day_sum=$canyu_model->where($map)->sum('money');
        $map['uid']=$userid;

       // dump($day_count);dump($day_sum);die;

        $user_num=$canyu_model->where($map)->count();
        if ($user_num>=C('play_times')) {
            die('<script>alert("今天已领过红包，请明天再来");history.back()</script>');
        }
        //每天的红包限制个数，限制总金额
        if ($day_count>=$number || $day_sum>=$total) {
            $this->display('missed');
            die();
        }

        //发放红包
        $avg=$day_sum/$day_count;
        if($avg>$total/$number){
            $money=1;
        }else{
            $money=rand(C('min'),C('max'));
        }
//        dump($day_sum);dump($money);dump(self::TOTAL);
        if ($day_sum+$money>$total) {
            $this->display('missed');
            die();
        }
//        dump(123);die;
        $data['uid']=$_SESSION['userid'];
        $data['is_win']=1;
        // $money = 1;
        $data['money']=$money;
        $canyu_model->add($data);
        $openid=M('User')->where('uid=%d',$userid)->getField('openid');
        // dump($openid);
        // dump($money);die;
        $this->send_redbag($openid, $money);
        // dump($money);die;
        // die;
        $this->assign('money',$money);
        $this->display('prize');
    }
    
    private function send_redbag($openid,$money) {
        header("Content-type:text/html;charset=utf-8");
        if (empty($openid) || empty($money)) {
            return false;
        }
        $money *= 100;//红包金额，单位分
        $mch_billno=MCHID.date('YmdHis').rand(1000, 9999);//订单号
        $act_name="美的空调送红包";//活动名称
        include_once("Common/wxhb/CommonUtil.php");
        $commonUtil = new CommonUtil();
        include_once('Common/wxhb/WxHongBaoHelper.php');
        $wxHongBaoHelper = new WxHongBaoHelper();
        $wxHongBaoHelper->appkey=C('appkey');
        $wxHongBaoHelper->setParameter("nonce_str", $commonUtil->create_noncestr());//随机字符串，丌长于 32 位
        $wxHongBaoHelper->setParameter("mch_billno", $mch_billno);//订单号
        $wxHongBaoHelper->setParameter("mch_id", C('mchid'));//商户号
        $wxHongBaoHelper->setParameter("wxappid", C('appid'));
        $wxHongBaoHelper->setParameter("nick_name", '闽南美的');//提供方名称
        $wxHongBaoHelper->setParameter("send_name", '闽南美的');//红包发送者名称
        $wxHongBaoHelper->setParameter("re_openid", $openid);//相对于医脉互通的openid
        $wxHongBaoHelper->setParameter("total_amount", $money);//付款金额，单位分
        $wxHongBaoHelper->setParameter("min_value", $money);//最小红包金额，单位分
        $wxHongBaoHelper->setParameter("max_value", $money);//最大红包金额，单位分
        $wxHongBaoHelper->setParameter("total_num", 1);//红包収放总人数
        $wxHongBaoHelper->setParameter("wishing", '我刚刚在美的抢到了大红包，天呐！五一节有现金可以花了！快来抢吧！');//红包祝福诧
        $wxHongBaoHelper->setParameter("client_ip", '127.0.0.1');//调用接口的机器 Ip 地址
        $wxHongBaoHelper->setParameter("act_name", $act_name);//活劢名称
        $wxHongBaoHelper->setParameter("remark", '告诉你的朋友一起来抢红包吧');//备注信息
        
        $wxHongBaoHelper->setParameter("logo_imgurl", 'http://xmhy.nidjia.com/public/images/logo.jpg');//商户logo的url
//      $wxHongBaoHelper->setParameter("share_content", '一起来抢[腾讯]红包吧');//分享文案
//      $wxHongBaoHelper->setParameter("share_url", RES_DOMAIN);//分享链接
//      $wxHongBaoHelper->setParameter("share_imgurl", RES_DOMAIN.'assets/images/getheadimg.jpg');//分享的图片url
        
        $postXml = $wxHongBaoHelper->create_hongbao_xml();
        $url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack';
        
        $responseXml = $wxHongBaoHelper->curl_post_ssl($url, $postXml);
        // var_dump($responseXml);
         // echo htmlentities($responseXml,ENT_COMPAT,'UTF-8');
        $responseObj = simplexml_load_string($responseXml, 'SimpleXMLElement', LIBXML_NOCDATA);
        $msg = $responseObj->return_code.','.$responseObj->return_msg;
        // echo $msg;
        
    }
    
    // public function show_jump() {
    //  $this->checklogin();
    //  $this->get_wx_share();
    //  $this->display('jump');
    // }
    
    public function get_wx_share() {
        $admin_model=M("Admin");
        $admin=$admin_model->where("aid=%d",1)->find();
        if (empty($admin['access_token']) || $admin['get_time']+$admin['expire_time']<time()) {
            //get token
            $token = $this->curl_post("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".C("appid")."&secret=".C("appsecret"));
            //file_put_contents('token.txt',$token);
            $token = json_decode($token,true);
            $access_token = $token['access_token'];
            $data['access_token'] = $access_token;
            $data['get_time'] = time();
            $data['expire_time'] = $token['expires_in'];
            $admin_model->where("aid=%d",1)->save($data);
        }else{
            $access_token = $admin['access_token'];
        }
         
        //get ticket
        $ticket = $this->curl_post("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=". $access_token ."&type=jsapi");
        //file_put_contents('ticket.txt',$ticket);
        $ticket_res = json_decode($ticket)->ticket;
         
        //create nonceStr
        $allChar = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $nonceStr = "";
        for ($i = 0; $i < 16; $i++) {
            $nonceStr .= substr($allChar, mt_rand(0, strlen($allChar) - 1), 1);
        }
         
        //create timestamp
        $timestamp = time();
         
        //get signature
        $tpStr = 'jsapi_ticket='.$ticket_res.'&noncestr='.$nonceStr.'&timestamp='.$timestamp.'&url=http://'.$_SERVER[HTTP_HOST].$_SERVER[REQUEST_URI];
        $signature = sha1($tpStr);
         
        $config="wx.config({
                    debug: false,
                    appId: '".C('appid')."',  //微信的appid需要在公众平台生成
                        timestamp: '$timestamp', //这是由php部分生成的
                        nonceStr: '$nonceStr', //这是由php部分生成的
                        signature: '$signature', //这是由php部分生成的
                        jsApiList: [
                        'onMenuShareTimeline',
                        'onMenuShareAppMessage',
                        'onMenuShareQQ',
                        'onMenuShareWeibo',
                        ]
        });";
        $this->assign('wx_config',$config);
    }


    function del_session(){
        unset($_SESSION['userid']);
        unset($_SESSION['openid']);
//        unset($_SESSION['access_token']);
    }
    // function monilogin(){
    //     $_SESSION['userid'] = '10531';
    //     $_SESSION['openid'] = 'oQzrmjpedUtjfGfPlN1G4VNgiXSg';
    // }
    
}